<template>
    <div :class='$style.addForm'>
        <XFormBox>
            <el-form ref='formRef' :rules='rules' :model='formData' size='small' label-position='top'>
                <el-form-item label='设备分类' prop='cate_2'>
                    <XLazyloadCascader class='w-100' valueField='code' labelField='name' v-model='deviceTypes' :level='2' :loadFunc='queryDictionaryOfDeviceTypeApi' @change='selectDeviceType' />
                </el-form-item>
                <el-form-item label='设备名称' prop='deviceName'>
                    <el-input type='text' clearable show-word-limit :maxlength='rules.deviceName[1].max' v-model='formData.deviceName' />
                </el-form-item>
                <el-form-item label='端口数' prop='portCount'>
                    <el-input type='text' clearable v-model.number='formData.portCount' />
                </el-form-item>
                <el-form-item label='物联卡'>
                    <XLazyloadSelect class='w-100' type='text' clearable  valueField='id' labelField='cardNo' :initQuery='initSelectQuery.simCardNo' :loadFunc='querySimByCardNoApi' v-model='formData.simId' />
                </el-form-item>
                <el-form-item label='所属商户'>
                    <XLazyloadSelect class='w-100' type='text' clearable  valueField='merchantId' labelField='merchantName' :initQuery='initSelectQuery.merchantName' :loadFunc='queryMerchantNameApi' v-model='formData.merchantId' />
                </el-form-item>
                <el-form-item label='所在地区'>
                    <XLazyloadCascader class='w-100' valueField='id' labelField='name' v-model='districts' :level='3' :loadFunc='getDistrictByParentIdApi' @change='selectDictrict' />
                </el-form-item>
                <el-form-item label='详细地址'>
                    <el-input type='text' maxlength='50' show-word-limit clearable v-model='formData.address' />
                </el-form-item>
                <el-form-item label='备注'>
                    <el-input type='textarea' :rows='3' maxlength='100' show-word-limit clearable v-model='formData.remark' />
                </el-form-item>
                <div class='text-center m-t-20'>
                    <XRequestButton :click='submit'>
                        <el-button type='primary'>确 定</el-button>
                    </XRequestButton>
                </div>
            </el-form>
        </XFormBox>
    </div>
</template>

<script lang='ts' setup>
    import { ElMessage } from 'element-plus'
    import { queryDictionaryOfDeviceTypeApi } from '../../../api/dictionary'
    import { getDistrictByParentIdApi } from '../../../api/district'
    import { queryMerchantNameApi } from '../../../api/merchant'
    import { querySimByCardNoApi } from '../../../api/iotsim'
    import { addDeviceApi, editdeviceApi, getdeviceEditDataApi } from '../../../api/device'
    import { filterEmpty } from '../../../utils'
    import { reactive, ref } from 'vue'
    import { useRoute, useRouter } from 'vue-router'
    import { useStore } from 'vuex'

    const $store = useStore()

    let deviceId = ref(0)
    
    const formData = reactive<any>({
        cate_1 : null,
        cate_2 : null,
        deviceName : null,
        portCount : null,
        simId : null,
        merchantId : null,
        provinceId : null,
        cityId : null,
        districtId : null,
        address : null,
        remark : null
    })
    let deviceTypes = reactive<any[]>([])
    let districts = reactive<string[]>([])
    let initSelectQuery = reactive({
        simCardNo : '',
        merchantName : ''
    })
    const rules = reactive<{[key in (keyof (typeof formData))]? : any}>({
        cate_2 : [
            {
                required : true,
                message : '请选择设备分类'
            }
        ],

        deviceName : [
            {
                required : false,
                message : '请输入设备名'
            },
            {
                min : 2,
                max : 15,
                message: '设备名长度在2-15之间',
            }
        ],

        portCount : [
            {
                required : true,
                message : '请输入端口数量'
            },
            {
                type : 'number',
                min : 1,
                max : 100,
                message : '端口数量在1-100之间'
            }
        ]
    })

    const formRef = ref()
    const route = useRoute()
    const router = useRouter()

    function selectDeviceType(e) {
        formData.cate_1 = e ? e[0] : ''
        formData.cate_2 = e ? e[1] : ''
    }

    function selectDictrict(e) {
        formData.provinceId =  e ? e[0] : ''
        formData.cityId =  e ? e[1] : ''
        formData.districtId =  e ? e[2] : ''
    }

    async function submit() {
        try {
            await formRef.value.validate()
            const data = {...formData}
            if(!deviceId.value) { //新增
                filterEmpty(data)
                const res = await addDeviceApi(data)
                if(res.success) {
                    ElMessage.success!('增加成功')
                }else {
                    ElMessage.error!(res.msg)
                    return
                }
            }else {
                if(data.simId === '') {
                    data.simId = 0
                }
                if(data.merchantId === '') {
                    data.merchantId = 0
                }

                const res = await editdeviceApi(deviceId.value, data)
                if(res.success) {
                    ElMessage.success!('编辑成功')
                }else {
                    ElMessage.error!(res.msg)
                    return
                }
            }

            router.go(-1)
            
        } catch (error) {
            
        }
    }

    async function init() {
        if(route.params.deviceId) {
            deviceId.value = Number(route.params.deviceId)
            const data:typeof formData = await getdeviceEditDataApi(deviceId.value)
            
            if(!data) {
                ElMessage.error!('数据不存在')
                useRouter().go(-1)
            }else {
                for(let k in formData) {
                    if(k in data) {
                        if(k == 'simId' || k == 'merchantId') {
                            if(data[k] == 0) {
                                data[k] = null
                            }
                        }
                        formData[k] = data[k]
                    }
                }

                if(data.simCardNo) {
                    initSelectQuery.simCardNo = data.simCardNo
                }
                if(data.merchantName) {
                    initSelectQuery.merchantName = data.merchantName
                }

                if(formData.cate_1 > 0) {
                    deviceTypes.push(formData.cate_1)
                }
                if(formData.cate_2 > 0) {
                    deviceTypes.push(formData.cate_2)
                }

                if(formData.provinceId > 0) {
                    districts.push(formData.provinceId)
                }
                if(formData.cityId > 0) {
                    districts.push(formData.cityId)
                }
                if(formData.districtId > 0) {
                    districts.push(formData.districtId)
                }
            }
        }
    }

    init()

    

</script>

<style scoped lang='scss' module>
    .addForm{
        margin: auto;
        max-width: 600px;
    }
</style>